package edu.suda.xsap.controller;

import edu.suda.xsap.common.Result;
import edu.suda.xsap.dto.MemberDto;
import edu.suda.xsap.entity.Member;
import edu.suda.xsap.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@RestController
@RequestMapping("/member")
@Slf4j
public class MemberController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/list")
    public Result list() {
        try {
            List<MemberDto> members = memberService.findAll();
            return Result.success(members);
        } catch (Exception e) {
            log.error("获取后端数据失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
    @PostMapping("/add")
    public Result save(@RequestBody Member memberDto) {
        log.info("memberDto:{}", memberDto);

        try {
            memberService.save(memberDto);
            return Result.success();
        } catch (Exception e) {
            log.error("保存数据失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
    @PutMapping("/update")
    public Result update(@RequestBody Member memberDto) {
        log.info("memberDto:{}", memberDto);
        try {
            memberService.update(memberDto);
            return Result.success();
        } catch (Exception e) {
            log.error("更新数据失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }
    @DeleteMapping("delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        try {
            memberService.delete(id);
            return Result.success();
        } catch (Exception e) {
            log.error("删除数据失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    @GetMapping("/search")
    public Result search(@RequestParam("query") String query) {
        try {
            List<MemberDto> members = memberService.searchByQuery(query);
            return Result.success(members);
        } catch (Exception e) {
            log.error("获取后端数据失败", e);
            return Result.failure(e.getMessage(), e);
        }
    }

    //会员绑定post请求，将会员与会员卡绑定
//    @PostMapping("/bind")
//    public Result bind(@RequestParam("memberId") Integer memberId, @RequestParam("cardId") Integer cardId) {
//        try {
//            memberService.bind(memberId, cardId);
//            return Result.success();
//        } catch (Exception e) {
//            log.error("绑定数据失败", e);
//            return Result.failure(e.getMessage(), e);
//        }
//    }

}

